package com.auth.filter;

import com.alibaba.fastjson.JSON;
import com.auth.custom.LoginUserInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.auth.common.result.Result;
import com.auth.common.result.ResultCodeEnum;
import com.auth.utils.ResponseUtils;
import com.auth.utils.StringPool;
import jwt.JwtHelperUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Author:Tangjiachang
 * @Date 2023/7/16
 * @Description:
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    private final RedisTemplate redisTemplate;
    public TokenAuthenticationFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 如果是登录url则放行
        if (StringPool.LOGIN_URL.equals(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return ;
        }
        // 返回null则说明认证失败
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if(null != authentication) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request, response);
        } else {
            ResponseUtils.out(response, request,Result.build(null, ResultCodeEnum.PERMISSION));
        }
    }

    public UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token置于header里
        String token = request.getHeader(StringPool.TOKEN);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtHelperUtils.getUsername(token);
            if (StringUtils.isNotEmpty(username)) {
                // 将当前信息存储到LoginUserInfoHelper中
                LoginUserInfoHelper.setUseId(JwtHelperUtils.getUserId(token));
                LoginUserInfoHelper.setUsername(username);
                List<SimpleGrantedAuthority> authorities = new ArrayList<>(0);
                // 通过用户名称从redis获取权限数据
                String auth = (String) redisTemplate.opsForValue().get(username);
                if (StringUtils.isNotEmpty(auth)) {
                    List<Map> maps = JSON.parseArray(auth, Map.class);
                    maps.stream().forEach(map -> {
                        authorities.add(new SimpleGrantedAuthority(String.valueOf(map.get("authority"))));
                    });
                }
                return new UsernamePasswordAuthenticationToken(username, null, authorities);
            }
        }
        return new UsernamePasswordAuthenticationToken(JwtHelperUtils.getUsername(token), null, Collections.EMPTY_LIST);
    }
}
